var express = require('express');
var router = express.Router();
var {userModel} = require('../database/model/jobModel.js')
var bcrypt = require('bcryptjs');
var salt = bcrypt.genSaltSync(10); //生成加密盐
var jwt = require('jsonwebtoken')
var secret = 'afs;dlkfa;sdlfka;lsdikf5464654654sadasd' //私钥
// 注册
router.post('/', function(req, res, next) {
  console.log(req.body);
  let {username,password} = req.body
  // 判断账号是否可用
  userModel.find({username}).then(result=>{
    if(result.length){ // 用户是否存在
      res.send({
        code:102,
        msg:'账号已被占用'
      })
      return
    }
    // 密码加密
    var hash = bcrypt.hashSync(password, salt); //密码加密
    // 向数据库存储用户
    new userModel({
      username,
      password:hash
    }).save().then(result=>{
      res.send({
        code:101,
        msg:'注册成功'
      })
    })
  })
});

// 登录
router.get('/', function(req, res, next) {
  console.log(req.query);
  let {username,password} = req.query
  userModel.find({username}).then(result=>{
    if(!result.length){
      res.send({
        code:102,
        msg:'账号不存在，请注册'
      })
      return
    }
    let hash = result[0].password  //提取数据库加密密码
    let bool = bcrypt.compareSync(password,hash) //密码比对
    if(!bool){
      res.send({
        code:103,
        msg:'密码错误，请重试'
      })
      return
    }
    let {username,avatar,_id} = result[0]
    //签发token，方便后续验证账号安全性
    let token = jwt.sign({
      time:Date.now(), //签发时间
      // limit:7*24*60*60*1000
      limit:2*60*60*1000 //约定有效时间
    },secret)
    res.send({
      code:101,
      msg:'登录成功',
      data:{
        username,avatar,_id,
        token
      }
    })
  })
});

// 用户信息更新（换头像）
router.put('/',(req,res)=>{
  console.log(req.query,req.body);
  userModel.updateOne(req.query,req.body).then(result=>{
    res.send({
      code:101,
      msg:'头像上传成功'
    })
  })
})

module.exports = router;
